package com.guoju.tyframework.mvc;

import java.io.IOException;
import java.lang.reflect.Proxy;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guoju.tyframework.mvc.action.Action;
import com.guoju.tyframework.mvc.action.ActionHandler;
import com.guoju.tyframework.mvc.config.ActionConfiguration;
import com.guoju.tyframework.mvc.config.MvcBeans;

public class CoreServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	//配置文件地址
	private String actionConfigLocation;
	

	public String getActionConfigLocation() {
		return actionConfigLocation;
	}

	public void setActionConfigLocation(String actionConfigLocation) {
		this.actionConfigLocation = actionConfigLocation;
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		String path=getServletPath(req);
		System.out.println("配置文件需要的path:"+path);
		Map<String,ActionConfiguration> configMap=(Map<String,ActionConfiguration>)this.getServletContext().getAttribute(ServletConstants.CONTEXT_ACTION_CONFIG);
		ActionConfiguration actionConfig=configMap.get(path);
		
		//String beanClass=actionConfig.getBeanClass();
		Map<String,String> actionResut=actionConfig.getResults();
		String view="";
		try {
			String actionClass= actionConfig.getActionClass();
			ActionHandler handler=new ActionHandler((Action)Class.forName(actionClass).newInstance());
			Action action=(Action) Proxy.newProxyInstance(Action.class.getClassLoader(),
						new Class[]{Action.class}, handler);
			MvcBeans actionBean=actionConfig.getActionBean();
			Object obj1=action.execute(actionBean,actionResut,req, resp);
			view=obj1.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		req.getRequestDispatcher(view).forward(req, resp);
	}
	
	
	private String getServletPath(HttpServletRequest req){
		String path=req.getServletPath();
		System.out.println("request.getServletPath()="+path);
		return path.split("\\.")[0];
	}

}
